import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Typography,
  TextField,
  Alert,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  ListItemButton,
  Chip,
  Divider,
} from '@mui/material';
import {
  PersonAdd,
  History,
  Delete,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { roomApi } from '@/services/api';
import { isValidRoomId, extractRoomIdFromUrl, getRecentRooms, saveRecentRoom, clearRecentRooms } from '@/utils/helpers';
import { ERROR_MESSAGES } from '@/utils/constants';
import Loading from '../common/Loading';

interface RecentRoom {
  roomId: string;
  timestamp: number;
  url?: string;
}

const JoinRoom: React.FC = () => {
  const [roomInput, setRoomInput] = useState('');
  const [isJoining, setIsJoining] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [recentRooms, setRecentRooms] = useState<RecentRoom[]>([]);
  
  const navigate = useNavigate();

  useEffect(() => {
    // 加载最近访问的房间
    const recent = getRecentRooms();
    setRecentRooms(recent);
  }, []);

  const handleJoinRoom = async (roomId?: string) => {
    const targetRoomId = roomId || extractRoomIdFromUrl(roomInput) || roomInput.trim();
    
    if (!targetRoomId) {
      setError('请输入房间ID或房间链接');
      return;
    }

    if (!isValidRoomId(targetRoomId)) {
      setError('房间ID格式不正确');
      return;
    }

    setIsJoining(true);
    setError(null);

    try {
      // 检查房间是否存在
      const roomExists = await roomApi.exists(targetRoomId);
      
      if (!roomExists) {
        setError('房间不存在或已过期');
        return;
      }

      // 保存到最近访问记录
      saveRecentRoom(targetRoomId);
      
      // 导航到房间页面
      navigate(`/room/${targetRoomId}`);
    } catch (error: any) {
      console.error('加入房间失败:', error);
      setError(error.message || ERROR_MESSAGES.UNKNOWN_ERROR);
    } finally {
      setIsJoining(false);
    }
  };

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRoomInput(event.target.value);
    setError(null);
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      handleJoinRoom();
    }
  };

  const handleClearRecentRooms = () => {
    clearRecentRooms();
    setRecentRooms([]);
  };

  const formatTimestamp = (timestamp: number) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    if (diffDays < 7) return `${diffDays}天前`;
    
    return date.toLocaleDateString('zh-CN');
  };

  if (isJoining) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <Loading message="正在加入房间..." size={48} />
      </Box>
    );
  }

  return (
    <Box sx={{ maxWidth: 500, mx: 'auto' }}>
      <Box sx={{ textAlign: 'center', mb: 4 }}>
        <Typography variant="h5" gutterBottom sx={{ fontWeight: 600 }}>
          加入视频通话房间
        </Typography>
        <Typography variant="body1" color="text.secondary">
          输入房间ID或粘贴房间链接即可加入通话
        </Typography>
      </Box>

      <Card elevation={2} sx={{ borderRadius: 2, mb: 3 }}>
        <CardContent sx={{ p: 3 }}>
          <TextField
            fullWidth
            label="房间ID或房间链接"
            placeholder="输入房间ID或粘贴完整的房间链接"
            value={roomInput}
            onChange={handleInputChange}
            onKeyPress={handleKeyPress}
            variant="outlined"
            sx={{ mb: 3 }}
            helperText="支持输入房间ID（如：abc123）或完整链接"
          />
          
          <Button
            fullWidth
            variant="contained"
            size="large"
            startIcon={<PersonAdd />}
            onClick={() => handleJoinRoom()}
            disabled={isJoining || !roomInput.trim()}
            sx={{
              py: 1.5,
              fontSize: '1.1rem',
              borderRadius: 2,
              boxShadow: 3,
              '&:hover': {
                boxShadow: 6,
                transform: 'translateY(-2px)',
              },
              transition: 'all 0.3s ease',
            }}
          >
            加入房间
          </Button>
        </CardContent>
      </Card>

      {/* 最近访问的房间 */}
      {recentRooms.length > 0 && (
        <Card elevation={1} sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <History color="action" />
                <Typography variant="h6" sx={{ fontWeight: 600 }}>
                  最近访问
                </Typography>
              </Box>
              <Button
                size="small"
                startIcon={<Delete />}
                onClick={handleClearRecentRooms}
                color="error"
                variant="text"
              >
                清空
              </Button>
            </Box>
            
            <Divider sx={{ mb: 1 }} />
            
            <List dense>
              {recentRooms.map((room, index) => (
                <ListItem key={`${room.roomId}-${index}`} disablePadding>
                  <ListItemButton
                    onClick={() => handleJoinRoom(room.roomId)}
                    sx={{
                      borderRadius: 1,
                      '&:hover': {
                        backgroundColor: 'action.hover',
                      },
                    }}
                  >
                    <ListItemText
                      primary={
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <Typography variant="body1" sx={{ fontFamily: 'monospace' }}>
                            {room.roomId}
                          </Typography>
                          <Chip
                            label={formatTimestamp(room.timestamp)}
                            size="small"
                            variant="outlined"
                            color="primary"
                          />
                        </Box>
                      }
                      secondary="点击快速加入此房间"
                    />
                  </ListItemButton>
                </ListItem>
              ))}
            </List>
          </CardContent>
        </Card>
      )}

      {/* 错误提示 */}
      {error && (
        <Alert
          severity="error"
          onClose={() => setError(null)}
          sx={{ mt: 2 }}
        >
          {error}
        </Alert>
      )}
    </Box>
  );
};

export default JoinRoom;